package org.example.queue;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class LargestValues {
    public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;this.right = right;
      }
    }

    /**
     * 给定一棵二叉树的根节点 root ，请找出该二叉树中每一层的最大值。
     * @param root
     * @return
     */
    public List<Integer> largestValues(TreeNode root) {
        //层序遍历，记录每层的最大值即可，用队列加宽搜
        List<Integer> ret = new ArrayList<>();
        if(null == root) return ret;
        Queue<TreeNode> queue = new LinkedList();
        queue.add(root);
        while(!queue.isEmpty()){
            int count = queue.size();
            int tmp = Integer.MIN_VALUE;
            while(count--!=0){
                TreeNode cur =queue.poll();
                tmp = Math.max(tmp,cur.val);
                if(cur.left!=null) queue.add(cur.left);
                if(cur.right!=null) queue.add(cur.right);
            }
            ret.add(tmp);
        }
        return ret;
    }
}
